package com.kamistoat.meimeistore.order.config;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.kamistoat.common.runTimeFunc.RunTimeLog;
import com.kamistoat.meimeistore.order.vo.PayVo;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@ConfigurationProperties(prefix = "alipay")
@Component()
@Data
public class AlipayTemplate {

    //在支付宝创建的应用的id
    private String app_id = "2021000118657105";

    // 商户私钥，您的PKCS8格式RSA2私钥
    private String merchant_private_key = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCaVL9LCLWqyxw2pb3I+0sw1zFqNNZnQFMjjt1jCfb9VZK9ZsufBAJCTu3JXAao+3AlEEaJO/rsmFphRT9vJUB6yt0i3RbHtcglf6QskI/+vjRADMMlIp+YN7HMcCQ6/Ty9r7Xg1xPSw5Rd5JUSTcYe4aqlAMDCI12jRzWsKIH1TS/yAUwg4q9sdQWxoHI8LOdjqh+6NoLxUpWhnhyVyBoCetLOLi6grbVoTLdSgEsov6vVjag0auvGeZu4b/CYe2+IGGEe5Zw3wyE9RTqQ4YEr6zZ/uyP0vNkYwki+kX/3Zhza7gjhaoOBw0SHk9gB3BFzVs+9uHAGuCApE9wklJK9AgMBAAECggEAFAJi3uadLyywVsF8br9uC0ILTRrWpYJohRazy3ByTnw2z0mxosdRR6mWGOJOlsAq1RNcIdTd/qjuJuhkhhONXZ5Jt4h0uKXv8jSvY3vGv5+HhLpi3sCzcnfeHIR5nhBRPMK4URNxpYToCphlX38n7b8Scdw8Ia+WJ2JHKjACUXxh3P/a0avnCm/PHhH1m8uyZMT4bJYjKYt7j3njXzhd/oNNgCBsii1OSwhinTxO0NrcM8ez7CGnEPM1bsyuXAk71a9WlAegMjQSA51OzeXE3urZO447BqN46JyOJr2a24afPTrCXU0tWJK8AjIbfA8zg6eSYQq4Q1J59y/QpWkyAQKBgQDQ3ft4e9enOIXqfZZV/LQUuBNp5DK+fvHjzogN3PaUg8R0fx04Pslz5kt4xrKz2D0A+v+B0gRxIIX4jqC3odTziEpf8SwiHIXXhNSDVpoNwSf3t9EVq4S3wV4xkZ6SedjAm6zW3tZ5XDn+lFjG8zlrmGuOlrWR1vN3Sgji5jBdPQKBgQC9KEcHoViAIiH56kh8TeTq4R2ecI5OBafLUHdvysCsXTNmfaWYZOi7GGo4zZNSSSOFQ7SxZrixdqwSN0X7wFdfFBsgBNWUcZQ7TGuzqpR+73x4KcHJcmO9UB23z4dKnO5w1ETp0iVULejSl05MUIFWvh0dpI2CUv76tbamSzNjgQKBgBqa7BlgzQuD66r+7FNvqRCqke5/HuedC/rUqAf8CXzJfBDK0FIFzWtx/lMYHFNETCD/1+QVeHNgjTAoGtjJSHLs/WxTMCf4MiRNyzQfp+fwnsKzK3LzMiil/PWbcvN9idqe+dk08WTsFocTJmvRN5M5CxpSoDY/hyu+xnsAj1CRAoGAOQeeurczhpZD5iRzrD6T6RjsJCvNS8q6tzrQd70KcC09ZQY22gZ6gIYw6GVaqHFyqygpn17YCnE8GdXeXLO14+2c6/9pIXNI/MPiqO2iDc9ImLYGPiUl2xr/ir6gDKfZ39yv1ktMg9+/lVaW/b078ZoqDxjgrU02oQIOSn7bxIECgYBZkPqjCNyt2CLZyawSmsLUcRfRLx1eJ0RjT/Dk7WiLNr4CiLQXoGDadchLS3fTTqgF4pl7qpJprqEUy5am4sPIrkwlv8l42pYSCAnmw5XiLtIqFV/qx0nEnIQXIuEc41U+RZ2+4LgdE/d5B1zLhQpTdnahp4n7Wh0ZCt8Fjxj1Uw==";

    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    private String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhoEM90yNgK+zMR44I/vcDjh+30wH/XJePAsFtJ3tAxGe6ta8he7Gq1RvuAlPckwpUg79NbvJmruXuEQDB4UrEYi3ru4Hra/eh69BTYVIQHk3LofaR75D4SkzfnoJD1QbvY2XhaOw7pDhcf4BrRLJp7xkZ2U0KRkTjJfllctew8No8284c4hFvO6xKR+23oQokz+ZEKS1Gy7Z+Qln7VbrrXY8WNAvCwpFn30nBkL3FrKcmwg8OWCFuyjnD1MzqUM7rS89Ckxi3E3+HN4ICyDPsof0NGsUh4PPvV7va6HYSV0ZUev9OSwdysW9nXoGGNR5KTPh7Ht4LpP8jKRdQr7cdwIDAQAB";

    // 服务器[异步通知]页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    // 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息
    // 当前项目下使用内网穿透来解决这个问题
    private String notify_url = "http://1wtvrcw44w.gz.aeert.com/payed/notify";

    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    // 同步通知，支付完成后的跳转页，一般跳转到成功页
    private String return_url = "http://order.meimeistore.com/orderlist.html";

    // 签名方式
    private String sign_type = "RSA2";

    // 字符编码格式
    private String charset = "utf-8";

    // 支付宝网关； https://openapi.alipaydev.com/gateway.do
    private String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";

    /**
     * 获取支付宝支付通道
     * @param vo
     * @return
     * @throws AlipayApiException
     */
    public String pay(PayVo vo) throws AlipayApiException {

        //AlipayClient alipayClient = new DefaultAlipayClient(AlipayTemplate.gatewayUrl, AlipayTemplate.app_id, AlipayTemplate.merchant_private_key, "json", AlipayTemplate.charset, AlipayTemplate.alipay_public_key, AlipayTemplate.sign_type);
        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
                app_id, merchant_private_key, "json",
                charset, alipay_public_key, sign_type);

        //2、创建一个支付请求 //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = vo.getOut_trade_no();
        //付款金额，必填
        String total_amount = vo.getTotal_amount();
        //订单名称，必填
        String subject = vo.getSubject();
        //商品描述，可空
        String body = vo.getBody();
        // 自动收单时间。超过该时间将停止本次支付，这里是支付接口幂等性的第一重保障，保证支付接口的过期时间比订单过期时间短。此处设置为1分钟
        // 支付宝提供两个收单时间参数。支付宝推荐使用 time_expire，当两者同时传入时，优先使用time_expire
        String timeout_express = "1m";  // timeout_express，设置相对时间长度
        String time_expire =
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
                        format(new Date(new Date().getTime() + 1000 * 60));  // time_expire，设置绝对过期时间，时间格式为yyyy-MM-dd HH:mm:ss

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
//                + "\"time_expire\":\"" + time_expire + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
        System.out.println("支付宝的响应：" + result);
        return result;
    }



    /**
     * 手动关闭支付通道。当订单被成功支付或者过期取消时，手动关闭该支付通道
     *
     * @return
     * @throws AlipayApiException
     */
    public void close(String orderSN) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
                app_id, merchant_private_key, "json",
                charset, alipay_public_key, sign_type);

        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();

        // 设置要关闭的支付通道的orderSN
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", orderSN);

        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = alipayClient.execute(request);

        RunTimeLog.printRunTimeLog("尝试手动关闭该订单的支付宝支付通道。订单SN:" + orderSN);
        if (response.getCode().equals("10000")) {
            RunTimeLog.printRunTimeLog("关闭成功");
        } else {
            RunTimeLog.printRunTimeLog("手动关闭支付通道失败，失败原因:" + response.getSubMsg() + "，请检查本地日志");
        }

        // 该方法不必关心返回值
        // 要么成功关闭支付通道
        // 要么支付宝已经发现该支付通道不是 待支付 状态，此时返回啥并不重要，因为确实也达到了关闭支付通道的目的
    }
}
